#! /bin/bash

# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 - 2022 by Apex.AI Inc. All rights reserved.
# SPDX-FileCopyrightText: © Contributors to the iceoryx-rs project
# SPDX-FileContributor: Mathias Kraus

# This script adds the issue number of the branch name to the commit message if it is available

set -eu

COLOR_RESET='\033[0m'
COLOR_RED='\033[1;31m'
COLOR_GREEN='\033[1;32m'
COLOR_YELLOW='\033[1;33m'

BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
BRANCH_ISSUE_NUMBER='0'

if [[ "${BRANCH_NAME}" =~ ^iox-[0-9]+ ]]; then
    BRANCH_ISSUE_NUMBER="$(echo "${BRANCH_NAME}" | grep -Eo 'iox-[0-9]+' | grep -Eo '[0-9]+')"
else
    echo -e "${COLOR_YELLOW}"
    echo -e "Warning: The branch name doesn't follow the convention of 'iox-ISSUE_NUMBER'."
    echo -e "Commit message won't be autoformatted."
    echo -e "${COLOR_RESET}"
    exit 0
fi

COMMIT_MSG=$(cat $1)
if [[ ${COMMIT_MSG} =~ ^iox-#[0-9]+ ]]; then
    COMMIT_ISSUE_NUMBER="$(echo "${COMMIT_MSG}" | grep -Eo 'iox-#[0-9]+' | grep -Eo '[0-9]+')"
    if [[ "${COMMIT_ISSUE_NUMBER}" != "${BRANCH_ISSUE_NUMBER}" ]]; then
        echo -e "${COLOR_YELLOW}"
        echo -e "Warning: Commit message issue number does not fit to branch issue number: '${BRANCH_ISSUE_NUMBER}'"
        echo -e "Is this on purpose?"
        echo -e "Commit message will not be autoformatted."
        echo -e "${COLOR_RESET}"
        exit 0
    fi
else
    echo -e "${COLOR_GREEN}"
    echo -e "Info: Commit message does not start with issue number: '${COMMIT_MSG}'"
    echo -e "Commit message will be autoformatted."
    echo -e "${COLOR_RESET}"
    echo -e "iox-#${BRANCH_ISSUE_NUMBER} ${COMMIT_MSG}" > $1
fi
